package com.cy.aircompressor.db;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.room.Room;

import com.cy.aircompressor.db.dao.AuthDao;
import com.drug.lib.util.DLog;
import com.net.model.utils.MD5;

import static com.drug.lib.base.BaseApplication.mContext;


public class DemoDbHelper {
    private static DemoDbHelper instance;
    private AppDatabase mDatabase;
    private final MutableLiveData<Boolean> mIsDatabaseCreated = new MutableLiveData<>();

    private DemoDbHelper() {
    }

    public static DemoDbHelper getInstance() {
        if (instance == null) {
            synchronized (DemoDbHelper.class) {
                if (instance == null) {
                    instance = new DemoDbHelper();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化数据库
     */
    public void initDb() {

        String userMd5 = MD5.encrypt2MD5("db_helper");
        // 以下数据库升级设置，为升级数据库将清掉之前的数据，如果要保留数据，慎重采用此种方式
        // 可以采用addMigrations()的方式，进行数据库的升级
        String dbName = String.format("db_%1$s.db", userMd5);
        DLog.i("db name = " + dbName);
        mDatabase = Room.databaseBuilder(mContext, AppDatabase.class, dbName)
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build();
        mIsDatabaseCreated.postValue(true);
    }

    public LiveData<Boolean> getDatabaseCreatedObservable() {
        return mIsDatabaseCreated;
    }

    /**
     * 关闭数据库
     */
    public void closeDb() {
        if (mDatabase != null) {
            mDatabase.close();
            mDatabase = null;
        }
    }

    public AuthDao getAuthDao() {
        if (mDatabase != null) {
            return mDatabase.userDao();
        }
        DLog.i("get userDao failed, should init db first");
        return null;
    }
}
